package com.hmdp.service.impl;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.Result;
import com.hmdp.entity.SeckillVoucher;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.SeckillVoucherMapper;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.hmdp.utils.SimpleRedisLock;
import com.hmdp.utils.UserHolder;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.aop.framework.AopContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Collections;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {

    @Resource
    private ISeckillVoucherService seckillVoucherService;

    @Resource
    private SeckillVoucherMapper seckillVoucherMapper;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private RedissonClient redissonClient;

    @Resource
    private Snowflake snowflake;

    @Resource
    private KafkaTemplate<String, VoucherOrder> kafkaTemplate;

    public static final DefaultRedisScript<Long> seckill_script;

    static {
        seckill_script = new DefaultRedisScript<>();
        seckill_script.setLocation(new ClassPathResource("seckill.lua"));
        seckill_script.setResultType(Long.class);
    }

    @Override
    public Result seckillVoucher(Long voucherId) {
        Long userId = UserHolder.getUser().getId();
        //执行lua脚本
        long r = stringRedisTemplate.execute(seckill_script,
                Collections.emptyList(),
                voucherId.toString(),
                userId.toString());

        //判断返回结果
        if (r != 0) {
            return Result.fail(r == 1 ? "库存不足": "不能重复下单");
        }

        //todo 将下单信息保存到mq
        VoucherOrder voucherOrder = new VoucherOrder();
        long orderId = snowflake.nextId();
        voucherOrder.setId(orderId);
        voucherOrder.setUserId(userId);
        voucherOrder.setVoucherId(voucherId);

        // IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();
        // proxy.createVoucherOrderAsync(voucherOrder);
        kafkaTemplate.send("order-topic", voucherOrder);

        return Result.ok(orderId);
    }



    // @Override
    // public Result seckillVoucher(Long voucherId) {
    //     // 1 查询优惠券
    //     // SeckillVoucher voucher = seckillVoucherMapper.selectByIdForUpdate(voucherId);
    //     SeckillVoucher voucher = seckillVoucherService.getById(voucherId);
    //
    //     // 2 判断秒杀是否开始
    //     if (voucher.getBeginTime().isAfter(LocalDateTime.now())) {
    //         return Result.fail("秒杀尚未开始");
    //     }
    //
    //     // 3 判断秒杀是否结束
    //     if (voucher.getEndTime().isBefore(LocalDateTime.now())) {
    //         return Result.fail("秒杀已经结束");
    //     }
    //     // 4 判断库存是否充足
    //     if (voucher.getStock() < 1) {
    //         return Result.fail("库存不足");
    //     }
    //
    //     Long userId = UserHolder.getUser().getId();
    //     //SimpleRedisLock lock = new SimpleRedisLock("voucher:" + userId, stringRedisTemplate);
    //     RLock lock = redissonClient.getLock("voucher:" + userId);
    //     boolean success = lock.tryLock();
    //     if (!success) {
    //         return Result.fail("不允许重复下单");
    //     }
    //     try {
    //         IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();
    //         return proxy.createVoucherOrder(voucherId);
    //     } finally {
    //         // 释放锁
    //         lock.unlock();
    //     }
    // }

    @Async("myExecutor")
    public void createVoucherOrderAsync(VoucherOrder voucherOrder) {
        save(voucherOrder);
    }

    @Transactional
    public Result createVoucherOrder(Long voucherId) {
        // 一人一单
        Long userId = UserHolder.getUser().getId();

        Long count = query().eq("user_id", userId).eq("voucher_id", voucherId).count();
        if (count > 0) {
            return Result.fail("用户已经购买过一次");
        }

        // 5 扣减库存
        boolean success = seckillVoucherService.update()
                .setSql("stock = stock - 1")
                .gt("stock", 0)
                .eq("voucher_id", voucherId).update();
        if (!success) {
            return Result.fail("库存不足");
        }


        // 6 创建订单
        long orderId = IdUtil.getSnowflake().nextId();
        VoucherOrder voucherOrder = new VoucherOrder();
        voucherOrder.setId(orderId);
        voucherOrder.setUserId(UserHolder.getUser().getId());
        voucherOrder.setVoucherId(voucherId);
        save(voucherOrder);

        // 7 返回订单ID
        return Result.ok(orderId);
    }
}
